package cn.nzcong.jpress.addon.articlesync.interceptor;


import com.jfinal.handler.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


public class ArticleSyncAddonHandler extends Handler {
    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
//        System.out.println("ArticleSyncAddonHandler invoked for target : " + target);

        // 内置属性
        request.setAttribute("domain", getServerDomain(request));
        // 处理前端多级属性，转换为JSONObject 放入request.attibute， 例如：user[age] = 23
        Map<String, Object> paramMap = new HashMap<>();
        for(Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()){
            handleParam(paramMap, entry.getKey(),
                    entry.getValue().length < 1 ? "" :
                            entry.getValue().length < 2 ? entry.getValue()[0]
                                    : entry.getValue());
        }
        for(Map.Entry<String, Object> entry : paramMap.entrySet()){
            request.setAttribute(entry.getKey(), entry.getValue());
        }
        next.handle(target, request, response, isHandled);
    }

    public static void handleParam(Map<String, Object> paramMap, String key, Object value){
        String paramKey = key;
        if(key.matches(".+?\\[.+\\]")){
            paramKey = key.substring(0, key.indexOf("["));
            paramMap.putIfAbsent(paramKey, new HashMap<String, Object>());
            String childKey = key.substring(key.indexOf("[") + 1, key.length() - 1);
            handleParam((HashMap)paramMap.get(paramKey), childKey, value);
        } else {
            paramMap.put(paramKey, value);
        }
    }

    public static String getServerDomain(HttpServletRequest request){
        StringBuffer sb = new StringBuffer(50)
                .append(request.getServerName());
        if(request.getServerPort() != 80 && request.getServerPort() != 443){
            sb.append(":").append(request.getServerPort());
        }
        return sb.toString();
    }

}
